
//
//  MallProductDetailViewController.m
//  MeterMart
//
//  Created by ENERGY on 2018/9/16.
//  Copyright © 2018年 ENERGY. All rights reserved.
//

#import "MallProductDetailViewController.h"
#import "MallProductDetailCollectionViewCell.h"
#import "ConfirmOrderViewController.h"
#import <SDCycleScrollView/SDCycleScrollView.h>
#import <WebKit/WebKit.h>
#import "ShareView.h"
#import "ShoppingCartTool.h"
#import "PhoneRegisterViewController.h"
#import "CommonViewController.h"
#import "WeChatLoginViewController.h"
#define NUMBERS @"0123456789\n"
@interface MallProductDetailViewController ()<UINavigationControllerDelegate, SDCycleScrollViewDelegate, UITextFieldDelegate, WKUIDelegate, WKNavigationDelegate, UICollectionViewDelegate, UICollectionViewDataSource>
@property (nonatomic, strong)UITableView * tableView;
@property (nonatomic, strong)UIView * headerView;
@property (nonatomic, strong)SDCycleScrollView * cycleScrollView;
@property (nonatomic, strong)UILabel * produceTitleLab;//商品标题
@property (nonatomic, strong)UILabel * soldNumLab;//已出售
@property (nonatomic, strong)UILabel * groupBuyingContentLab;//团购
@property (nonatomic, strong)UITextField * buyNumTextField;//购买数量
@property (nonatomic, strong)UILabel * repertoryLab;//库存
@property (nonatomic, strong)UIView * footerView;
@property (nonatomic, strong)WKWebView * webView;
@property (nonatomic, assign)int webH;//web页的高度
@property (nonatomic, strong)ShareView * shareView;//分享页面
@property (nonatomic, strong)NSString * codeString;//微信登录回调code
@property (nonatomic, strong)UILabel * specificationLab;//规格
@property (nonatomic, strong)UICollectionView * collectionView;
@property (nonatomic, strong)UICollectionViewFlowLayout * layout;
@property (nonatomic, strong)NSMutableArray * itemArr;
@property (nonatomic, strong)UIView * middleWhiteView;
@property (nonatomic, strong)UIButton * addCartBtn;//加入购物车按钮
@property (nonatomic, strong)UIButton * cartBtn;//购物车按钮
/** 商品数量label */
@property (nonatomic, strong) UILabel *goodsNumLabel;
@property (nonatomic, strong)NSDictionary * model;//模型
@property (nonatomic, strong)NSString * produceType;//产品规格
@property (nonatomic, strong)NSString * ifPay;//1为没交会员钱，0为已交会员钱
@property (nonatomic, strong)UIButton * shareBtn;//分享按钮
@property (nonatomic, strong)NSString * shareURL;//分享地址
@property (nonatomic, strong)NSString * goodsTitle;//商品标题
@property (nonatomic, strong)NSString * goodsDescribe;//商品描述
@property (nonatomic, strong)NSString * phoneString;
@property (nonatomic, strong)NSString * tokenString;
- (void)produceNumAnimate;//购物车动画效果
- (void)weChatShareURL:(int)scene;//分享
- (void)ifLogin;
@end

@implementation MallProductDetailViewController(networking)
//商品详情
- (void)getProduceDetailData{
    NSDictionary * dic = @{
                           @"id":self.produceID
                           };
    [self showprogressHUD];
    [[AFAppDotNetAPIClient sharedClient] POST:@"detailsiosapi/index" parameters:dic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [self hiddenProgressHUD];
        if ([responseObject[@"sign"] isEqualToString:@"1"]) {
            self.model = [NSDictionary dictionaryWithDictionary:responseObject[@"list"]];
            self.shareURL = responseObject[@"list"][@"url"];
        }else if ([[NSString stringWithFormat:@"%@", responseObject[@"sign"]] isEqualToString:@"400"]) {
            [self ifLogin];
        }else{
            ShowMessage(responseObject[@"msg"]);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self showError:error];
        [self hiddenProgressHUD];
    }];
}
//加入购物车
- (void)addProduceToCart{
    NSDictionary * dic = @{
                           @"token":self.tokenString,
                           @"phone":self.phoneString,
                           @"goodsid":self.produceID,
                           @"goodssum":self.buyNumTextField.text,
                           @"handlength":self.produceType
                           };
    [self showprogressHUD];
    [[AFAppDotNetAPIClient sharedClient] POST:@"cartApi/iosaddShoppingCar" parameters:dic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [self hiddenProgressHUD];
        if ([[NSString stringWithFormat:@"%@", responseObject[@"sign"]] isEqualToString:@"1"]) {
            [self getCartProduceNum];//购物车商品数量
        }else if ([[NSString stringWithFormat:@"%@", responseObject[@"sign"]] isEqualToString:@"400"]) {
            [self ifLogin];
        }else{
            ShowMessage(responseObject[@"msg"]);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self hiddenProgressHUD];
        [self showError:error];
    }];
}
//购物车商品数量
- (void)getCartProduceNum{
    NSDictionary * dic = @{
                           @"token":self.tokenString,
                           @"phone":self.phoneString
                           };
    [[AFAppDotNetAPIClient sharedClient] POST:@"cartApi/iosshoppingCarCount" parameters:dic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if ([responseObject[@"sign"] isEqualToString:@"1"]) {
            [self produceNumAnimate];
            if ([[NSString stringWithFormat:@"%@", [responseObject[@"list"] objectForKey:@"count"]] isEqualToString:@"0"]) {
                self.goodsNumLabel.hidden = YES;
            }else{
                self.goodsNumLabel.hidden = NO;
                self.goodsNumLabel.text = [NSString stringWithFormat:@"%@", [responseObject[@"list"] objectForKey:@"count"]];
            }
        }else if ([[NSString stringWithFormat:@"%@", responseObject[@"sign"]] isEqualToString:@"400"]) {
            
        }else{
            ShowMessage(responseObject[@"msg"]);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self showError:error];
    }];
}
@end
@implementation MallProductDetailViewController
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.navigationItem.title = @"商品详情";
    [self.navigationController setNavigationBarHidden:NO animated:YES];
    
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    if (@available(iOS 11.0, *)) {
        self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }else {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    //分享按钮
    UIButton * shareBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 25/WIDTH_6_SCALE, 25/WIDTH_6_SCALE)];
    [shareBtn setImage:[UIImage imageNamed:@"share"] forState:UIControlStateNormal];
    [shareBtn addTarget:self action:@selector(shareBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    self.shareBtn = shareBtn;
    UIBarButtonItem * rightButtonItem = [[UIBarButtonItem alloc] initWithCustomView:shareBtn];
    self.navigationItem.rightBarButtonItem = rightButtonItem;
    if (![WXApi isWXAppInstalled]) {
        self.shareBtn.hidden = YES;
    }
    
    if ([[UserModel sharedInstanced].token isEqualToString:@""] || [UserModel sharedInstanced].token == nil || [[UserModel sharedInstanced].token length] == 0 || [[UserModel sharedInstanced].mobile isEqualToString:@""] || [UserModel sharedInstanced].mobile == nil || [[UserModel sharedInstanced].mobile length] == 0) {
        self.tokenString = @"";
        self.phoneString = @"";
    }else{
        self.tokenString = [UserModel sharedInstanced].token;
        self.phoneString = [UserModel sharedInstanced].mobile;
    }
    //tableView
    [self.view addSubview:self.tableView];
    [self getProduceDetailData];
    [self setUpBottomBar];//底部栏
    [self getCartProduceNum];//购物车商品数量
    
}
#pragma mark - init
- (ShareView *)shareView{
    if (!_shareView) {
        __weak typeof (self)weakSelf = self;
        _shareView = [[ShareView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - BOTTOM_HEIGHT)];
        _shareView.friendBtnClickBlock = ^{
            [weakSelf wxShare:0];
        };
        _shareView.circleBtnClickBlock = ^{
            [weakSelf wxShare:1];
        };
    }return _shareView;
}
- (void)setModel:(NSDictionary *)model{
    _model = model;
    NSDictionary * produceDetailDic = [NSDictionary dictionaryWithDictionary:model[@"details"][0]];//商品详情
    NSMutableArray * produceSpecificationsArr = @[].mutableCopy;
    [produceSpecificationsArr addObjectsFromArray:model[@"guige"]];
    NSArray * arr = @[produceDetailDic[@"goodsimg1"], produceDetailDic[@"goodsimg2"]];
    self.cycleScrollView.imageURLStringsGroup = arr;
    self.produceTitleLab.text = [NSString stringWithFormat:@"%@  %@", produceDetailDic[@"goodsname"], produceDetailDic[@"goodsdescribe"]];
    self.goodsTitle = produceDetailDic[@"goodsname"];
    self.goodsDescribe = produceDetailDic[@"goodsdescribe"];
    self.soldNumLab.text = [NSString stringWithFormat:@"已售 %@  件", produceDetailDic[@"soldnum"]];
    self.groupBuyingContentLab.text = [NSString stringWithFormat:@"团购价 ￥%@", produceDetailDic[@"groupprice"]];
    //粗体
    NSMutableAttributedString *attrString = [[NSMutableAttributedString alloc] initWithString:self.groupBuyingContentLab.text];
    UIFont *boldFont = [UIFont boldSystemFontOfSize:16];
    [attrString addAttribute:NSFontAttributeName value:boldFont range:[self.groupBuyingContentLab.text rangeOfString:[NSString stringWithFormat:@"%@", produceDetailDic[@"groupprice"]]]];
    // 设置颜色
    [attrString addAttribute:NSForegroundColorAttributeName value:getColor(mainRedColor) range:[self.groupBuyingContentLab.text rangeOfString:[NSString stringWithFormat:@"%@", produceDetailDic[@"groupprice"]]]];
    self.groupBuyingContentLab.attributedText = attrString;
    
    self.repertoryLab.text = [NSString stringWithFormat:@"库存  %@", produceDetailDic[@"stocknum"]];
    if (produceDetailDic[@"goodsdetails"] == nil || [produceDetailDic[@"goodsdetails"] length] == 0 || [produceDetailDic[@"goodsdetails"] isEqualToString:@""]) {
        
    }else{
        [self showprogressHUD];
        [self.webView loadHTMLString:produceDetailDic[@"goodsdetails"] baseURL:nil];
    }
    if (produceSpecificationsArr.count == 1) {
        self.specificationLab.hidden = YES;
        self.collectionView.hidden = YES;
        self.headerView.frame = CGRectMake(0, 0, SCREEN_WIDTH, 495/WIDTH_6_SCALE);
        [self.middleWhiteView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.height.mas_offset(58/WIDTH_6_SCALE);
        }];
    }else{
        self.specificationLab.hidden = NO;
        self.collectionView.hidden = NO;
        [self.itemArr addObjectsFromArray:produceSpecificationsArr];
        [self.collectionView reloadData];
        self.headerView.frame = CGRectMake(0, 0, SCREEN_WIDTH, 555/WIDTH_6_SCALE);
        [self.middleWhiteView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.height.mas_offset(118/WIDTH_6_SCALE);
        }];
    }
}
- (NSMutableArray *)itemArr{
    if (!_itemArr) {
        _itemArr = @[].mutableCopy;
    }return _itemArr;
}
- (UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - BOTTOM_HEIGHT - 60/WIDTH_6_SCALE - NAVI_HEIGHT)];
        _tableView.backgroundColor = getColor(mainColor);
        _tableView.tableHeaderView = self.headerView;
        _tableView.tableFooterView = self.footerView;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    }return _tableView;
}
- (UIView *)headerView{
    if (!_headerView) {
        _headerView = [[UIView alloc] init];
        _headerView.frame = CGRectMake(0, 0, SCREEN_WIDTH, 627/WIDTH_6_SCALE);
        _headerView.backgroundColor = getColor(mainColor);
        [self setUpTableViewHeaderViews];
    }return _headerView;
}
- (UIView *)footerView{
    if (!_footerView) {
        _footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 1)];
        _footerView.backgroundColor = getColor(mainColor);
        //        首先是关键JS代码：
        NSString *jScript =
        @"var meta = document.createElement('meta'); meta.setAttribute('name', 'viewport'); meta.setAttribute('content', 'width=device-width'); document.getElementsByTagName('head')[0].appendChild(meta); var imgs = document.getElementsByTagName('img');for (var i in imgs){imgs[i].style.maxWidth='100%';imgs[i].style.height='auto';}"
        ;
        //        然后初始化并加入JS片段：
        WKUserScript *wkUScript = [[WKUserScript alloc] initWithSource:jScript injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
        WKUserContentController *wkUController = [[WKUserContentController alloc] init];
        [wkUController addUserScript:wkUScript];
        WKWebViewConfiguration *wkWebConfig = [[WKWebViewConfiguration alloc] init];
        wkWebConfig.userContentController = wkUController;
        self.webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 0) configuration:wkWebConfig];
        self.webView.scrollView.bounces = NO;
        self.webView.scrollView.showsHorizontalScrollIndicator = NO;
        self.webView.scrollView.scrollEnabled = NO;
        self.webView.navigationDelegate = self;
        [_headerView addSubview:self.webView];
        
    }return _footerView;
}
- (void)setUpTableViewHeaderViews{
    __weak typeof (self)weakSelf = self;
    //上部白色底
    UIView * topWhiteView = [[UIView alloc] init];
    topWhiteView.backgroundColor = [UIColor whiteColor];
    [_headerView addSubview:topWhiteView];
    //返回按钮
    UIButton * backBtn = [[UIButton alloc] init];
    [_headerView addSubview:backBtn];
    [backBtn setImage:[UIImage imageNamed:@"back"] forState:UIControlStateNormal];
    UIButton * backCoverBtn = [[UIButton alloc] init];//返回覆盖按钮
    [_headerView addSubview:backCoverBtn];
    [backCoverBtn addTarget:self action:@selector(backBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    //商品图片
    self.cycleScrollView = [[SDCycleScrollView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 190/WIDTH_6_SCALE)];
    self.cycleScrollView.placeholderImage = [UIImage imageNamed:@"YimiPlaceHolder"];
    self.cycleScrollView.delegate = self;
    self.cycleScrollView.pageControlAliment = SDCycleScrollViewPageContolAlimentCenter;
    self.cycleScrollView.currentPageDotColor = [UIColor whiteColor];
    self.cycleScrollView.bannerImageViewContentMode = UIViewContentModeScaleToFill;
    self.cycleScrollView.pageControlAliment = SDCycleScrollViewPageContolAlimentCenter;
    self.cycleScrollView.clickItemOperationBlock = ^(NSInteger index) {
        NSLog(@">>>>>  %ld", (long)index);
//        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:weakSelf.cycleArr[index][@"url"]] options:nil completionHandler:nil];
    };
    [_headerView addSubview:self.cycleScrollView];
    //商品标题
    self.produceTitleLab = [[UILabel alloc] init];
    self.produceTitleLab.text = @"---";
    self.produceTitleLab.font = DEF_FontSize_16;
    self.produceTitleLab.textColor = [UIColor blackColor];
    self.produceTitleLab.lineBreakMode = 0;
    self.produceTitleLab.numberOfLines = 2;
    [_headerView addSubview:self.produceTitleLab];
    //已出售
    self.soldNumLab = [[UILabel alloc] init];
    [self label:self.soldNumLab withFont:DEF_FontSize_10 withText:[NSString stringWithFormat:@"已售 --  件"] withTextColor:getColor(textGrayColor) withTextAlignment:NSTextAlignmentLeft withView:_headerView];
    //团购价
    self.groupBuyingContentLab = [[UILabel alloc] init];
    [self label:self.groupBuyingContentLab withFont:DEF_FontSize_10 withText:[NSString stringWithFormat:@"团购价 ￥---"] withTextColor:getColor(textGrayColor) withTextAlignment:NSTextAlignmentLeft withView:_headerView];
    //代理价
    //masonry
    [topWhiteView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.right.equalTo(weakSelf.headerView);
        make.height.mas_offset(417/WIDTH_6_SCALE);
    }];
    [backCoverBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(backBtn.mas_centerX);
        make.centerY.equalTo(backBtn.mas_centerY);
        make.width.height.mas_offset(25/WIDTH_6_SCALE);
    }];
    [self.cycleScrollView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(weakSelf.headerView.mas_left);
        make.right.equalTo(weakSelf.headerView.mas_right);
        make.top.equalTo(topWhiteView.mas_top).mas_offset(10/WIDTH_6_SCALE);
        make.height.mas_offset(293/WIDTH_6_SCALE);
    }];
    [self.produceTitleLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(weakSelf.headerView.mas_left).mas_offset(20/WIDTH_6_SCALE);
        make.right.equalTo(weakSelf.headerView.mas_right).mas_offset(-20/WIDTH_6_SCALE);
        make.top.equalTo(weakSelf.cycleScrollView.mas_bottom).mas_offset(13/WIDTH_6_SCALE);
        make.height.mas_offset(40/WIDTH_6_SCALE);
    }];
    [self.soldNumLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(weakSelf.produceTitleLab);
        make.top.equalTo(weakSelf.produceTitleLab.mas_bottom).mas_offset(9/WIDTH_6_SCALE);
    }];
    [self.groupBuyingContentLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(weakSelf.soldNumLab.mas_bottom).mas_offset(9/WIDTH_6_SCALE);
        make.left.equalTo(weakSelf.soldNumLab.mas_left);
    }];
    
    [self setUpMiddleWhiteView];
}
- (void)setUpMiddleWhiteView{
    //中间白色背景
    UIView * middleWhiteView = [[UIView alloc] init];
    middleWhiteView.backgroundColor = [UIColor whiteColor];
    self.middleWhiteView = middleWhiteView;
    [_headerView addSubview:middleWhiteView];
    //数量
    UILabel * numTitleLab = [[UILabel alloc] init];
    [self label:numTitleLab withFont:DEF_FontSize_16 withText:@"数量" withTextColor:[UIColor blackColor] withTextAlignment:NSTextAlignmentLeft withView:middleWhiteView];
    //减号
    UIButton * minusBtn = [[UIButton alloc] init];
    [minusBtn setBackgroundImage:[UIImage imageNamed:@""] forState:UIControlStateNormal];
    [self button:minusBtn withBGColor:[UIColor clearColor] withLayerBorderColor:getColor(@"898989") withLayerBorderWith:1 withCornerRadius:0 withMasksToBounds:NO withViwe:middleWhiteView];
    [minusBtn setTitleColor:getColor(textGrayColor) forState:UIControlStateNormal];
    [minusBtn setTitle:@"—" forState:UIControlStateNormal];
    [minusBtn addTarget:self action:@selector(minusBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [middleWhiteView addSubview:minusBtn];
    //购买数量
    self.buyNumTextField = [[UITextField alloc] init];
    self.buyNumTextField.text = @"1";
    self.buyNumTextField.delegate = self;
    self.buyNumTextField.font = DEF_FontSize_16;
    self.buyNumTextField.layer.borderWidth = 1;
    self.buyNumTextField.textColor = [UIColor blackColor];
    self.buyNumTextField.layer.borderColor = getColor(textGrayColor).CGColor;
    self.buyNumTextField.textAlignment = NSTextAlignmentCenter;
    [middleWhiteView addSubview:self.buyNumTextField];
    //加号
    UIButton * plusBtn = [[UIButton alloc] init];
    [plusBtn setBackgroundImage:[UIImage imageNamed:@""] forState:UIControlStateNormal];
    [self button:plusBtn withBGColor:[UIColor clearColor] withLayerBorderColor:getColor(textGrayColor) withLayerBorderWith:1 withCornerRadius:0 withMasksToBounds:NO withViwe:middleWhiteView];
    [plusBtn setTitleColor:getColor(textGrayColor) forState:UIControlStateNormal];
    [plusBtn setTitle:@"+" forState:UIControlStateNormal];
    [plusBtn addTarget:self action:@selector(plusBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [middleWhiteView addSubview:plusBtn];
    //库存
    self.repertoryLab = [[UILabel alloc] init];
    [self label:self.repertoryLab withFont:DEF_FontSize_10 withText:@"库存   --" withTextColor:getColor(textGrayColor) withTextAlignment:NSTextAlignmentRight withView:middleWhiteView];
    //规格
    self.specificationLab = [[UILabel alloc] init];
    [self label:self.specificationLab withFont:DEF_FontSize_16 withText:@"规格" withTextColor:[UIColor blackColor] withTextAlignment:NSTextAlignmentLeft withView:middleWhiteView];
    //collectionView
    self.layout = [[UICollectionViewFlowLayout alloc] init];
    self.layout.estimatedItemSize = CGSizeMake(60/WIDTH_6_SCALE, 30/WIDTH_6_SCALE);// layout约束这边必须要用estimatedItemSize才能实现自适应,使用itemSzie无效
    self.layout.scrollDirection =  UICollectionViewScrollDirectionHorizontal;
    self.layout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 20/WIDTH_6_SCALE);
    // 设置 最小列间距
    self.layout.minimumInteritemSpacing  = 10/WIDTH_6_SCALE;
    self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:self.layout];
    self.collectionView.showsHorizontalScrollIndicator = NO;
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    self.collectionView.backgroundColor = [UIColor clearColor];
    [self.collectionView registerClass:[MallProductDetailCollectionViewCell class] forCellWithReuseIdentifier:NSStringFromClass([MallProductDetailCollectionViewCell class])];
    [middleWhiteView addSubview:self.collectionView];
    //masonry
    __weak typeof (self)weakSelf = self;
    [middleWhiteView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(weakSelf.headerView);
        make.bottom.equalTo(weakSelf.headerView.mas_bottom).mas_offset(-10/WIDTH_6_SCALE);
        make.height.mas_offset(118/WIDTH_6_SCALE);
    }];
    [numTitleLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(middleWhiteView.mas_left).mas_offset(20/WIDTH_6_SCALE);
        make.top.equalTo(middleWhiteView.mas_top).mas_equalTo(14/WIDTH_6_SCALE);
        make.height.mas_offset(30/WIDTH_6_SCALE);
    }];
    [minusBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(numTitleLab.mas_right).mas_offset(20/WIDTH_6_SCALE);
        make.height.mas_offset(30/WIDTH_6_SCALE);
        make.centerY.equalTo(numTitleLab.mas_centerY);
        make.width.mas_offset(40/WIDTH_6_SCALE);
    }];
    [self.buyNumTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(minusBtn.mas_right).mas_offset(-1/WIDTH_6_SCALE);
        make.top.bottom.equalTo(minusBtn);
        make.width.mas_offset(63/WIDTH_6_SCALE);
    }];
    [plusBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(weakSelf.buyNumTextField.mas_right).mas_offset(-1/WIDTH_6_SCALE);
        make.height.width.equalTo(minusBtn);
        make.centerY.equalTo(minusBtn.mas_centerY);
    }];
    [self.repertoryLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(middleWhiteView.mas_right).mas_offset(-17/WIDTH_6_SCALE);
        make.centerY.top.equalTo(numTitleLab);
    }];
    [self.specificationLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(middleWhiteView.mas_left).mas_offset(20/WIDTH_6_SCALE);
        make.top.equalTo(numTitleLab.mas_bottom).mas_equalTo(25/WIDTH_6_SCALE);
        make.height.mas_offset(40/WIDTH_6_SCALE);
    }];
    [self.collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(minusBtn.mas_left);
        make.top.bottom.equalTo(weakSelf.specificationLab);
        make.right.equalTo(weakSelf.headerView.mas_right);
    }];
}
- (void)setUpBottomBar{
    //底部栏
    UIView * bottomBar = [[UIView alloc] init];
    bottomBar.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:bottomBar];
    //首页图片
    UIImageView * backHomeImg = [[UIImageView alloc] init];
    backHomeImg.image = [UIImage imageNamed:@"home"];
    [bottomBar addSubview:backHomeImg];
    //首页文字
    UILabel * backHomeLab = [[UILabel alloc] init];
    [self label:backHomeLab withFont:DEF_FontSize_10 withText:@"首页" withTextColor:getColor(textGrayColor) withTextAlignment:NSTextAlignmentCenter withView:bottomBar];
    //首页覆盖按钮
    UIButton * backHomeCoverBtn = [[UIButton alloc] init];
    backHomeCoverBtn.backgroundColor = [UIColor clearColor];
    [backHomeCoverBtn addTarget:self action:@selector(backHomeCoverBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [bottomBar addSubview:backHomeCoverBtn];
    //购物车图片
    self.cartBtn = [[UIButton alloc] init];
    [self.cartBtn setImage:[UIImage imageNamed:@"cart"] forState:UIControlStateNormal];
    [bottomBar addSubview:self.cartBtn];
    // 商品数量label
    self.goodsNumLabel = [[UILabel alloc] init];
    [bottomBar addSubview:self.goodsNumLabel];
    self.goodsNumLabel.backgroundColor = [UIColor redColor];
    self.goodsNumLabel.textColor = [UIColor whiteColor];
    self.goodsNumLabel.textAlignment = NSTextAlignmentCenter;
    self.goodsNumLabel.font = [UIFont systemFontOfSize:10];
    self.goodsNumLabel.layer.cornerRadius = 7;
    self.goodsNumLabel.clipsToBounds = YES;
    self.goodsNumLabel.text = @"";
    self.goodsNumLabel.hidden = YES;
    //购物车文字
    UILabel * cartLab = [[UILabel alloc] init];
    [self label:cartLab withFont:DEF_FontSize_10 withText:@"购物车" withTextColor:getColor(textGrayColor) withTextAlignment:NSTextAlignmentCenter withView:bottomBar];
    //购物车覆盖按钮
    UIButton * cartCoverBtn = [[UIButton alloc] init];
    cartCoverBtn.backgroundColor = [UIColor clearColor];
    [cartCoverBtn addTarget:self action:@selector(cartCoverBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [bottomBar addSubview:cartCoverBtn];
    //加入购物车
    UIButton * addCartBtn = [[UIButton alloc] init];
    [self button:addCartBtn withBGColor:getColor(@"30211d") withLayerBorderColor:nil withLayerBorderWith:0 withCornerRadius:0 withMasksToBounds:NO withViwe:bottomBar];
    [addCartBtn setTitle:@"加入购物车" forState:UIControlStateNormal];
    addCartBtn.titleLabel.font = DEF_FontSize_15;
    [addCartBtn addTarget:self action:@selector(addCartBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [addCartBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    self.addCartBtn = addCartBtn;
    //立即购买
    UIButton * buyNowBtn = [[UIButton alloc] init];
    [self button:buyNowBtn withBGColor:getColor(@"e92600") withLayerBorderColor:nil withLayerBorderWith:0 withCornerRadius:0 withMasksToBounds:NO withViwe:bottomBar];
    [buyNowBtn setTitle:@"立即购买" forState:UIControlStateNormal];
    buyNowBtn.titleLabel.font = DEF_FontSize_15;
    [buyNowBtn addTarget:self action:@selector(buyNowBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [buyNowBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    //masonry
    __weak typeof (self)weakSelf = self;
    [bottomBar mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(weakSelf.view);
        make.bottom.equalTo(weakSelf.view.mas_bottom).mas_offset(-BOTTOM_HEIGHT);
        make.height.mas_offset(60/WIDTH_6_SCALE);
    }];
    [backHomeImg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(bottomBar.mas_left).mas_offset(20/WIDTH_6_SCALE);
        make.top.equalTo(bottomBar.mas_top).mas_offset(14/WIDTH_6_SCALE);
        make.width.mas_offset(21/WIDTH_6_SCALE);
        make.height.mas_offset(19/WIDTH_6_SCALE);
    }];
    [backHomeLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(backHomeImg.mas_bottom);
        make.height.mas_offset(20/WIDTH_6_SCALE);
        make.centerX.equalTo(backHomeImg.mas_centerX);
    }];
    [backHomeCoverBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(backHomeImg.mas_top);
        make.bottom.equalTo(backHomeLab.mas_bottom);
        make.centerX.equalTo(backHomeImg.mas_centerX);
        make.width.mas_offset(22/WIDTH_6_SCALE);
    }];
    [self.cartBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(backHomeImg.mas_right).mas_offset(21/WIDTH_6_SCALE);
        make.top.equalTo(backHomeImg);
        make.width.height.mas_offset(20/WIDTH_6_SCALE);
    }];
    [cartLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(weakSelf.cartBtn.mas_bottom);
        make.height.mas_offset(20/WIDTH_6_SCALE);
        make.centerX.equalTo(weakSelf.cartBtn.mas_centerX);
    }];
    [cartCoverBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(bottomBar.mas_top);
        make.bottom.equalTo(bottomBar.mas_bottom);
        make.centerX.equalTo(weakSelf.cartBtn.mas_centerX);
        make.width.mas_offset(22/WIDTH_6_SCALE);
    }];
    [addCartBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(bottomBar.mas_top).mas_offset(4/WIDTH_6_SCALE);
        make.bottom.equalTo(bottomBar.mas_bottom).mas_offset(-4/WIDTH_6_SCALE);
        make.left.equalTo(weakSelf.cartBtn.mas_right).mas_offset(26/WIDTH_6_SCALE);
        make.right.equalTo(buyNowBtn.mas_left).mas_offset(-6/WIDTH_6_SCALE);
    }];
    [buyNowBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(bottomBar.mas_right).mas_offset(-6/WIDTH_6_SCALE);
        make.width.bottom.top.equalTo(addCartBtn);
    }];
    [self.goodsNumLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(weakSelf.cartBtn.mas_right).mas_offset(18/WIDTH_6_SCALE);
        make.centerY.equalTo(self.cartBtn.mas_top);
        make.width.mas_offset(25/WIDTH_6_SCALE);
        make.height.mas_offset(15/WIDTH_6_SCALE);
    }];
}
#pragma mark - collectionViewDelegate和collcetionViewDataSource
- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    MallProductDetailCollectionViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:NSStringFromClass([MallProductDetailCollectionViewCell class]) forIndexPath:indexPath];
    cell.model = self.itemArr[indexPath.row];
    return cell;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.itemArr.count;
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    for (int i = 0; i<self.itemArr.count; i++) {
        NSMutableDictionary * singleDic = [NSMutableDictionary dictionaryWithDictionary:self.itemArr[i]];
        if (i == indexPath.row) {
            [singleDic setObject:@"1" forKey:@"ifSelecte"];
        }else{
            [singleDic setObject:@"0" forKey:@"ifSelecte"];
        }
        [self.itemArr replaceObjectAtIndex:i withObject:singleDic];
    }
    self.produceType = [self.itemArr[indexPath.row] objectForKey:@"guige"];
    [self.collectionView reloadData];
}
#pragma mark - textFieldDelegate
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    NSCharacterSet *cs;
    if(self.buyNumTextField == textField){
        cs = [[NSCharacterSet characterSetWithCharactersInString:NUMBERS] invertedSet];
        NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];
        BOOL basicTest = [string isEqualToString:filtered];
        if(!basicTest){
            ShowMessage(@"请输入数字");
            return NO;
        }
    }
    //其他的类型不需要检测，直接写入
    return YES;
}
#pragma mark - WKWebViewDelegeta
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
    WS(ws)
    [webView evaluateJavaScript:@"document.body.offsetHeight;" completionHandler:^(id _Nullable any, NSError * _Nullable error) {
        [self hiddenProgressHUD];
        NSString *heightStr = [NSString stringWithFormat:@"%@",any];
        ws.webH = [heightStr intValue];
        self.webView.frame = CGRectMake(0, 0, SCREEN_WIDTH, self.webH);
        [self.footerView addSubview:self.webView];
        self.footerView.frame = CGRectMake(0, 0, SCREEN_WIDTH, self.webView.bottom);
        self.tableView.tableFooterView = self.footerView;
        [self hiddenProgressHUD];
        [self.tableView reloadData];
    }];
}
#pragma mark - action
- (void)ifLogin{
    WeChatLoginViewController * vc = [[WeChatLoginViewController alloc] init];
    UINavigationController* navi = [[UINavigationController alloc] initWithRootViewController:vc];
    vc.backHomePageBlock = ^{
        [vc dismissViewControllerAnimated:YES completion:nil];
        [self.tabBarController setSelectedIndex:0];
    };
    [self presentViewController:navi animated:YES completion:nil];
}
- (void)backBtnClick:(UIButton *)sender{
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)shareBtnClick:(UIButton *)sender{
    [self.shareView showView];
}
- (void)backHomeCoverBtnClick:(UIButton *)sender{
    NSLog(@"首页");
    [self.navigationController popToRootViewControllerAnimated:YES];
    [self.tabBarController setSelectedIndex:0];
}
- (void)cartCoverBtnClick:(UIButton *)sender{
    NSLog(@"购物车");
    [self.tabBarController setSelectedIndex:1];
    [self.navigationController popToRootViewControllerAnimated:YES];
}
//加入购物车
- (void)addCartBtnClick:(UIButton *)sender{
    if ([self.buyNumTextField.text isEqualToString:@""] || [self.buyNumTextField.text  isEqual: @""] || self.buyNumTextField.text == nil) {
        ShowMessage(@"请填写购买数量");
        return;
    }else{
        if (self.itemArr.count > 0) {
            if ([self.produceType isEqualToString:@""] || self.produceType == nil || [self.produceType length] == 0) {
                ShowMessage(@"请选择产品规格");
                return;
            }
        }
        if ([self.produceType isEqualToString:@""] || self.produceType.length == 0 || self.produceType == nil) {
            self.produceType = @"0";
        }
        if ([self.phoneString isEqualToString:@""] || self.phoneString == nil || [self.phoneString length] == 0 || [self.tokenString isEqualToString:@""] || self.tokenString == nil || [self.tokenString length] == 0) {
            [self ifLogin];
            return;
        }
        [self addProduceToCart];//加入购物车接口
    }
}
- (void)minusBtnClick:(UIButton *)sender{
    int num = [self.buyNumTextField.text intValue];
    num = num - 1;
    if (num<1) {
        num = 1;
    }
    NSString * finalStr = [[NSString alloc] initWithFormat:@"%d", num];
    self.buyNumTextField.text = finalStr;
}
- (void)plusBtnClick:(UIButton *)sender{
    int num = [self.buyNumTextField.text intValue];
    num = num + 1;
    NSString * finalStr = [[NSString alloc] initWithFormat:@"%d", num];
    self.buyNumTextField.text = finalStr;
}
//立即购买
- (void)buyNowBtnClick:(UIButton *)sender{
    ConfirmOrderViewController * confirmOrderListVC = [[ConfirmOrderViewController alloc] init];
    confirmOrderListVC.produceID = self.produceID;
    if ([self.buyNumTextField.text isEqualToString:@""] || [self.buyNumTextField.text  isEqual: @""] || self.buyNumTextField.text == nil) {
        ShowMessage(@"请填写购买数量");
        return;
    }else{
        if (self.itemArr.count > 0) {
            if ([self.produceType isEqualToString:@""] || self.produceType == nil || [self.produceType length] == 0) {
                ShowMessage(@"请选择产品规格");
                return;
            }
        }
        confirmOrderListVC.produceNum = self.buyNumTextField.text;
    }
    if ([self.produceType isEqualToString:@""] || self.produceType.length == 0 || self.produceType == nil) {
        self.produceType = @"0";
    }
    confirmOrderListVC.handlength = self.produceType;
    confirmOrderListVC.fromWhcichController = @"MallProductDetailViewController";
    [self.navigationController pushViewController:confirmOrderListVC animated:YES];
}
//分享
- (void)wxShare:(int)scene{
    NSLog(@"微信分享");
    if ([WXApi isWXAppInstalled] && [WXApi isWXAppSupportApi]) {
        [self weChatShareURL:scene];
    }else {
        // 提示用户安装微信
        ShowMessage(@"请安装微信");
    }
}
//分享
- (void)weChatShareURL:(int)scene{
    //创建发送对象实例
    SendMessageToWXReq *sendReq = [[SendMessageToWXReq alloc] init];
    sendReq.bText = NO;//不使用文本信息
    sendReq.scene = scene;//0 = 好友列表 1 = 朋友圈 2 = 收藏
    //创建分享内容对象
    WXMediaMessage *urlMessage = [WXMediaMessage message];
    urlMessage.title = self.goodsTitle;//分享标题
    urlMessage.description = self.goodsDescribe;//分享描述
    [urlMessage setThumbImage:[UIImage imageNamed:@"martLogo"]];//分享图片,使用SDK的setThumbImage方法可压缩图片大小
    //创建多媒体对象
    WXWebpageObject *webObj = [WXWebpageObject object];
    webObj.webpageUrl = [NSString stringWithFormat:@"%@?id=%@", self.shareURL, self.produceID];//分享链接
    //完成发送对象实例
    urlMessage.mediaObject = webObj;
    sendReq.message = urlMessage;
    //发送分享信息
    [WXApi sendReq:sendReq];
}
//商品数量动画
- (void)produceNumAnimate{
    [ShoppingCartTool addToShoppingCartWithGoodsImage:[UIImage imageNamed:@""] startPoint:self.addCartBtn.center endPoint:self.cartBtn.center completion:^(BOOL finished) {//添加动画图案
        NSLog(@"动画结束了");
        //------- 颤抖吧 -------//
        CABasicAnimation *scaleAnimation = [CABasicAnimation animationWithKeyPath:@"transform.scale"];
        scaleAnimation.fromValue = [NSNumber numberWithFloat:1.0];
        scaleAnimation.toValue = [NSNumber numberWithFloat:0.7];
        scaleAnimation.duration = 0.1;
        scaleAnimation.repeatCount = 1; // 颤抖两次
        scaleAnimation.autoreverses = YES;
        scaleAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
        [self.goodsNumLabel.layer addAnimation:scaleAnimation forKey:nil];
    }];
}
@end
